<?php
//对{op } ... {/op }的解析
function smarty_block_op(&$params, $content, &$smarty, &$repeat){
   return $smarty->callblockfunc($params,$content,$smarty,$repeat, getop);
}

/**
 * 参数：
 * 	viewname: 视图的名称
 *  opname: 视图下操作的名称
 * @param unknown_type $params
 */
function getop(&$params) {
	global $_db, $cf_updatecache, $cf_pagenum, $cf_opauthflg;
	
	if(!isset($_SESSION['_op_lastupdated'])) $_SESSION['_lastupdated'] = 0;
	$lastupdated = &$_SESSION['_op_lastupdated'];
	
	//#region 获取缓存的操作集
	if((time()-$lastupdated>$cf_updatecache ) || !isset($_SESSION['_ops'])){
		unset($_SESSION['_ops']);
		
		//对于超级用户,满足其所有权限
		if('-1'==$_SESSION['userid'] || !$cf_opauthflg){
			$sql = "select t.* from t_op t";
		}else{
			$sql = "select distinct t.* from t_op t
				left join t_roleop rv on rv.c_opid=t.c_id 
				left join t_userrole ur on ur.c_roleid=rv.c_roleid 
				left join t_user u on ur.c_userid=u.c_id where 1=1 and u.c_id='$_SESSION[userid]'";
		}
		$sql .= " order by c_updated desc";
		
		//获取结果集
		$res = $_db->query($sql);
		foreach ($res as $row){
			//$row = array("id"=>$row['c_id'], "viewname"=>$row['c_viewname'], "opname"=>$row['c_opname'], "desc"=>$row['c_desc']);
			$_SESSION['_ops'][$row['viewname']][$row['opname']] = $row;
			$_SESSION['_ops'][0][] = $row;
		}
		
		$_SESSION['_op_lastupdated'] = time();
	}
	//#endreg 获取缓存的操作集
	
	//#region 获取筛选结果集
	if(array_key_exists('id', $params)){
		if(empty($params['id'])){
			$res = null;
		}
		else{
			foreach($_SESSION['_ops'][0] as $op){
				if($params['id'] == $op['id']){
					$res = array($op);
					break;
				}
			}
		}
	}
	else if(!isempty(@$params['viewname']) && !isempty(@$params['opname'])){
		//error_log(print_r($_SESSION, 1));
		$op = @$_SESSION['_ops'][$params['viewname']][$params['opname']];
		if(null==$op) return null;
		$res = array($op);
	}
	else if(!isempty(@$params['viewname'])){
		$op = @$_SESSION['_ops'][$params['viewname']];
		if(null==$op) return null;
		$res = array();
		foreach ($op as $fname => $fall){
			$res[] = $fall;
		}
	}
	else{
		$res = $_SESSION['_ops'][0];
	}
	//#endreg 获取筛选结果集
		
	//#region 分页
	$params['totalcount'] = count($res);
	$params['pageindex'] = (!isset($params['pageindex']) || $params['pageindex']<0)?0:(int)$params['pageindex'];
	if(!array_key_exists('pagenum', $params)){
		$params['pagenum'] = $cf_pagenum;
	}
	if(0>=$params['pagenum']){
		$params['pagenum'] = $params['totalcount'];
	}
	else{
		$start = $params['pagenum']*$params['pageindex'];
		$end = $start + $params['pagenum'];
		$tmp = array();
		
		$i = 0;
		$end = $end < count($res) ? $end : count($res);
		for($i=$start; $i<$end; $i++){
			$tmp[] = $res[$i];
		}
		$res = $tmp;
	}
	//#endreg 分页
	
	return $res;
}
?>